import { showSuccessToast } from 'vant';
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { deserialize } from '@/plugins/reflect-metadata';
import type { ListState } from '@/types';
import camel2snake from '@/utils/camel2snake';
import convertQuery from '@/utils/convertQuery';
import pathReplace from '@/utils/pathReplace';

import { delOrderItem, getOrderList } from '../api';
import OrderItem, { OrderStatusConfig } from '../models/OrderItem';
import OrderList, { OrderQuery } from '../models/OrderList';

const useOrderList = () => {
  const route = useRoute();
  const router = useRouter();
  const { query } = route;

  const params = ref<OrderQuery>(new OrderQuery());
  const state = ref<ListState<OrderItem>>({
    data: [],
    loading: false,
    total: 0,
  });

  watch(
    () => params.value.params,
    () => {
      pathReplace(
        router,
        route,
        camel2snake({
          realName: params.value.realName,
          orderNo: params.value.orderNo,
          status: `${params.value.status}`,
        }),
      );
    },
  );

  const fetchData = async () => {
    try {
      state.value.loading = true;
      const { data } = await getOrderList(params.value);
      const resultData = deserialize(data, OrderList);
      state.value.data = resultData.items;
      state.value.total = resultData.total;
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  const config = ref<OrderStatusConfig>(new OrderStatusConfig());
  const handleUpdate = async (item: OrderItem) => {
    try {
      state.value.loading = true;
      config.value.orderNo = item.orderNo;
      const { data } = await delOrderItem(config.value);
      showSuccessToast(data.msg || '操作成功');
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };

  onMounted(async () => {
    params.value = deserialize(
      convertQuery(query, ['order_no', 'real_name', 'status']),
      OrderQuery,
    );
    await fetchData();
  });

  return {
    params,
    state,
    fetchData,
    handleUpdate,
  };
};

export default useOrderList;
